package middleware

import (
	"fmt"
	"multi-cloud-manage/config"
	"multi-cloud-manage/internal/storage"
	"multi-cloud-manage/pkg/cloud/huawei"
	"multi-cloud-manage/utils"

	"github.com/gin-gonic/gin"
)

// 中间件函数
func NewProvider() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 从数据库中获取当前用户的as，ak
		value, _ := c.Get("userID")
		userID := value.(int)
		fmt.Println("当前用户ID：", userID)
		uc, err := storage.GetAkByUserId(userID)
		if err != nil {
			c.JSON(200, gin.H{
				"code":    500,
				"message": "用户AS,SK不存在",
			})
			return
		}
		fmt.Println("加密：", uc.AK, uc.SK)
		key := config.GetConfig().Aescrypt.Key
		// 解密
		eak, _ := utils.GcmDecrypt(key, uc.AK)
		esk, _ := utils.GcmDecrypt(key, uc.SK)
		fmt.Println("解密：", eak, esk)
		// 实例化Provider对象
		provider := huawei.NewProvider(
			eak,
			esk,
			"cn-north-4",
			"08ff055c9f0010c22f86c00e4e888984",
		)
		// 将它保存到上下文中
		c.Set("provider", provider)
		c.Next()
	}
}
